package org.example.sys.controller.api.v1;

import org.example.sys.bean.ResponseData;
import org.example.sys.controller.api.ApiController;
import org.example.sys.model.Book;
import org.example.sys.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RequestMapping("/api/v1/book")
@RestController
public class BookController extends ApiController {

    @Autowired
    BookService bookService;

    @PostMapping()
    public ResponseData saveOrUpdate(@RequestBody Book book) {
        if (book.getId() == null || book.getId() == 0) {
            book.setId(null);
            bookService.save(book);
            return new ResponseData();
        } else {
            if (bookService.update(book)) {
                return new ResponseData();
            }
            return new ResponseData(FAILED, "modified is failed");
        }
    }

    @DeleteMapping(value = "{id}")
    public ResponseData delete(@PathVariable("id") Integer id) {
        return new ResponseData(bookService.deleteById(id) ? FAILED : SUCCESS);
    }

    @GetMapping(value = "{id}")
    public ResponseData find(@PathVariable("id") Integer id) {
        Book book = bookService.query(id);
        if (book == null) {
            return new ResponseData(FAILED, "this book is not found");
        }
        return new ResponseData().setData(book);
    }

    @GetMapping("/{pageNo}/{pageSize}")
    public ResponseData table(@PathVariable("pageNo") Integer pageNo, @PathVariable("pageSize") Integer pageSize) {
        return new ResponseData().setData(bookService.tableData(pageNo, pageSize));
    }
}
